package com.example.zip.controller;

import com.xiaoleilu.hutool.io.IoUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lizhongguang
 * @version 1.0
 * @date 2019/8/1 16:46
 */
@Controller
@RequestMapping(value = "test")
public class TestController {

	@GetMapping("")
	@ResponseBody
	public String test() {
		return "success";
	}

	@GetMapping("downloadZip")
	public void downloadZip(HttpServletRequest request, HttpServletResponse response) {
		//响应头的设置
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");

		//设置压缩包的名字
		//解决不同浏览器压缩包名字含有中文时乱码的问题
		try {
			String downloadName = "document.zip";
			//返回客户端浏览器的版本号、类型
			String agent = request.getHeader("USER-AGENT");
			try {
				//针对IE或者以IE为内核的浏览器：
				if (agent.contains("MSIE") || agent.contains("Trident")) {
					downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
				} else {
					//非IE浏览器的处理：
					downloadName = new String(downloadName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

			//设置压缩流：直接写入response，实现边压缩边下载
			ZipOutputStream zipOs;
			zipOs = new ZipOutputStream(response.getOutputStream());
			//设置压缩方法
			zipOs.setMethod(ZipOutputStream.DEFLATED);
			//循环将文件写入压缩流
			DataOutputStream os = new DataOutputStream(zipOs);
			String filename = "1156473249794760705.jpeg";
			File file = new File("D:\\wisdom_client\\credential\\鲁00001\\" + filename);
			if (file.exists()) {
				try {
					//添加ZipEntry，并ZipEntry中写入文件流
					zipOs.putNextEntry(new ZipEntry(filename));
					byte[] decode = IoUtil.readBytes(new FileInputStream(file));
					os.write(decode);
					zipOs.closeEntry();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//关闭流
			os.flush();
			os.close();
			zipOs.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
